/*
Copyright (C) THL A29 Limited, a Tencent company. All rights reserved.

SPDX-License-Identifier: Apache-2.0
*/

package main

import (
	"chainmaker.org/chainmaker/pb-go/v2/common"
	sdk "chainmaker.org/chainmaker/sdk-go/v2"
	"fmt"
	"context"
	"github.com/hokaccha/go-prettyjson"
	"log"

)

const (
	sdkConfigPKUser1Path     = "../sdk_configs/sdk_config_pk_user1.yml"
	sdkConfigOrg1Client1Path = "../sdk_configs/sdk_config_org1_client1.yml"
	onlyHeader				 = true
)


func main() {

	fmt.Println("初始化客户端")
	client, err := sdk.NewChainClient(
		sdk.WithConfPath(sdkConfigPKUser1Path),
		// sdk.WithConfPath(sdkConfigOrg1Client1Path),
	)
	
	if err != nil {
		log.Fatalln("创建client失败, 错误:" + err.Error())
	}
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	
	c, err := client.SubscribeBlock(ctx, -1, -1, true, onlyHeader)
	if err != nil {
		log.Fatalln(err)
	}

	for {
		select {
		case block, ok := <-c:
			// fmt.Println("=============================")
			// fmt.Println(block)
			// fmt.Println(ok)
			if !ok {
				fmt.Println("chan is close!")
				return
			}

			if block == nil {
				log.Fatalln("require not nil")
			}

			if onlyHeader {
				blockHeader, ok := block.(*common.BlockHeader)
				if !ok {
					log.Fatalln("require true")
				}

				fmt.Printf("recv blockHeader [%d] => %+v\n", blockHeader.BlockHeight, blockHeader)
			} else {
				fmt.Println("===============区块详情===================")
				blockInfo, ok := block.(*common.BlockInfo)
				if !ok {
					log.Fatalln("require true")
				}
				fmt.Println(blockInfo)
				marshal, err := prettyjson.Marshal(blockInfo)
				if err != nil {
					log.Fatalln(err)
				}
				fmt.Printf("blockInfo: %s\n", marshal)
				// fmt.Println("recv blockInfo [%d] => %+v\n", blockInfo.Block.Header.BlockHeight, blockInfo)
			}

			//if err := client.Stop(); err != nil {
			//	return
			//}
			//return
		case <-ctx.Done():
			return
		}
	}

}


